package com.xiongtian.stack;

import javax.xml.soap.Node;

/**
 * @author xiongtian
 * @version 1.0
 * @date 2021/3/18 17:19
 */
public class LinkedStackDemo {
    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack(5);
        for (int i = 1; i <= 5; i++) {
            stack.push(new MyNode(i));
        }
        stack.show();
        MyNode pop = stack.pop();
        System.out.println(pop.val);
        stack.show();
    }
}

class LinkedStack {

    private MyNode top = new MyNode(-1);
    private int maxSize;

    public LinkedStack(int maxSize) {
        this.maxSize = maxSize;
    }

    public boolean isFull() {
        return maxSize == size();
    }

    public boolean isEmpty() {
        return top.next == null;
    }

    public void push(MyNode newNode) {
        if (isFull()) {
            System.out.println("栈已满，无法入栈！");
        }
        newNode.next = top.next;
        top.next = newNode;
    }

    public MyNode pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈已空，无法出栈！");
        }
        MyNode resNode = top.next;
        top.next = top.next.next;
        return resNode;
    }

    public void show(){
        MyNode curNode = top.next;
        int i =size();
        while (curNode != null) {
            System.out.printf("stack[%d] = %d\n",i,curNode.val);
            curNode=curNode.next;
            i--;
        }
    }

    public int size() {
        MyNode cur = top.next;
        int num = 0;
        while (cur != null) {
            num++;
            cur = cur.next;
        }
        return num;
    }


}

class MyNode {
    public int val;
    public MyNode next;

    public MyNode(int val) {
        this.val = val;
    }

}
